require('./framwork.js')
// var testData = require('./TestData.js')
var W = 600;

var DIS = 80;
var MAX_NUM = 9;
var H = 750;


var DataEvent = {

  // RANK_KEY: "battleid",


  SHOW_VIEW: 'show_view',
  HIDE_VIEW: 'hide_view',
  SEND_DATA: 'send_data',

  CHANGE_DIR: 'sub_change_dir',

  INIT: 'viewport',

  FONT: '关'

}

function KVData(key, value, channelID) {
  this.key = key;
  if (channelID == 1) {
    this.value = JSON.stringify({
      "wxgame": {
        "score": value,
        "update_time": Date.now()
      }
    })
  } else {
    this.value = JSON.stringify({
      "ttgame": {
        "score": value,
        "update_time": Date.now()
      }
    })
  }

}

function RankModel(data /*: UserGameData*/, score) {
  this.data = data;
  this.score = score;
}

RankModel.prototype = {

  getKVDataList() {
    return this.data.KVDataList;
  },

  getOpenID() {
    return this.data.openid;
  },

  getScore() {

    return this.score;
  },

  getNickName() {
    return this.data.nickname;
  },

  getAwatarUrl() {
    return this.data.avatarUrl;
  }
}

function RankItem() {
  // this.node = new window.Node();
  // this.node.setContentSize(600,80)

  this.bg = loadSprite('SubGame/res/images/itembg.png', true)
  this.bg.setContentSize(W, DIS)
  this.label_name = loadText('', 28, cc.c3b(255, 255, 255))
  this.label_name.setAnchorPoint(0, 0.5)
  this.bg.add(this.label_name)
  this.label_score = loadText('', 28, cc.c3b(255, 255, 255))
  this.bg.add(this.label_score)
  this.label_num = loadText('', 28, cc.c3b(255, 255, 255))
  this.bg.add(this.label_num)
  this.icon = loadSprite('', false)
  this.icon.setContentSize(70, 70)
  this.bg.add(this.icon)
  // this.node.add(this.bg)
}



RankItem.prototype = {
  setVisible(flag) {
    // console.log(' RankItem setVisible ', flag)
    this.bg.setVisible(flag)
  },
  getChild() {
    return this.bg;
  },
  setPosition(x, y) {
    // this.bg.setPosition(x,y)
    this.label_name.setPosition(-100, 0)
    this.label_num.setPosition(-250, 0)
    this.icon.setPosition(-170, 0)
    this.label_score.setPosition(200, 0)
  },

  init(user, rank, x, y) {
    // console.log(' init ============================== ', user)
    // set nickName
    var nick = user.getNickName();
    console.log(' nick ', nick, nick.length)
    var num = 5;
    if (nick.length > num) {
      nick = nick.substring(0, num) + '...'
    }

    this.label_name.setString(nick)

    this.label_num.setString(rank)

    this.label_score.setString(user.getScore() + DataEvent.FONT)

    this.icon.loadTexture(user.getAwatarUrl());

  }
}


function RankView() {

  // this.key = DataEvent.RANK_KEY;
}

RankView.prototype = {
  setData(value, channelID) {
    let list = new Array()
    console.log('RankView setData ', value.key, value.value)
    list.push(new KVData(value.key, value.value, channelID))
    this.setUserCloudStorage(list, function () {
      // console.log(' set user data success ')
    })
  },

  init(x, y, w, h) {
    this.itemList = []
    this.rankMap = {}
    this.pageID = 0;
    this.maxPageNum = 0;
    // this.MAX_NUM = 9;
    this.loadFinish = true;
    viewRect = cc.rect(x, y, w, h)
    scene.setPosition(canvas.width / 2, canvas.height / 2)
    scene.removeAllChildren()
    this.list = scene.add(loadListView(cc.size(canvas.width, canvas.height), {
      itemMargin: 4
    }))

  },

  showView(value) {
    this.key = value.key;
    this.updateData();
  },

  updateData() {
    // console.log(' updateData ')
    if (this.loadFinish) {
      this.loadFinish = false;
      this.pageID = 0;
      this.rankMap = {}
      this.initFriendInfo([this.key], function (fData) {
        // console.log(' fdata ', fData)
        this.addData(fData)
        this.maxPageNum = Math.ceil(this.rankMap[this.key].length / MAX_NUM)
        this.updateContent();


      }.bind(this))
    }

  },

  setUserCloudStorage(dataList /*: Array<KVData>*/, callback) {
    console.log('setUserCloudStorage  ', dataList)
    wx.setUserCloudStorage({
      KVDataList: dataList,
      success: function (res) {
        callback(res.KVDataList)
        console.log('setUserCloudStorage  success ')
      },
      fail: function (e) {
        console.warn('setUserCloudStorage fail ', e)
      },
      complete: function () {

      }
    })
  },
  left() {
    if (this.maxPageNum > 0) {
      this.pageID--;
      if (this.pageID < 0) {
        this.pageID = this.maxPageNum - 1;
      }
      this.updateContent();
    }

  },

  right() {
    if (this.maxPageNum > 0) {
      this.pageID++;
      if (this.pageID > this.maxPageNum - 1) {
        this.pageID = 0;
      }
      this.updateContent();
    }

  },

  updateListView(position, item) {
    // console.log(' position ', position)
    // item.x = 0;
    let list = this.rankMap[this.key]
    if (list) {
      let rank = list[position]

      if (rank) {
        item.init(rank, position + 1)
        item.setVisible(true)
      } else {
        item.setVisible(false)
      }
    }
  },
  /**
   * 添加内容
   */
  updateContent() {
    let list = this.rankMap[this.key]
    if (!list) {
      console.log(' updateContent list is null ')
      return;
    }
    for (let index = 0; index < MAX_NUM; index++) {
      let pos = index + this.pageID * MAX_NUM
      let item = this.itemList[index]
      if (!item) {
        item = new RankItem();
        this.itemList[index] = item;
        this.list.add(item.getChild())
        item.setPosition(0, index * 82)
      } else {
        // console.log(' item is have ')
      }

      this.updateListView(pos, item)
    }

  },
  /**
   * 获得好友数据
   * @param callback 
   */
  initFriendInfo(keyList, callback) {
    var that = this;
    wx.getFriendCloudStorage({
      keyList: keyList,
      success: function (res) {

        callback(res.data)
        that.loadFinish = true;
      },
      fail: function (res) {
        console.error(res);
        that.loadFinish = true;
      }
    });
  },
  addData(data /*: UserGameData[]*/) {
    if (!data) {
      return;
    }
    console.log(' data.length =====================  ', data.length)
    let count = data.length
    for (let i = 0; i < count; i++) {
      const userData /*: UserGameData */ = data[i];
      let KVDataList = userData.KVDataList;
      if (KVDataList) {
        for (let index = 0; index < KVDataList.length; index++) {
          const element /*: KVData */ = KVDataList[index];
          if (!this.rankMap[element.key]) {
            this.rankMap[element.key] = []
          }
          let value = JSON.parse(element.value)
          if (value.wxgame) {
            this.rankMap[element.key].push(new RankModel(userData, value.wxgame.score))
          } else if (value.ttgame) {
            this.rankMap[element.key].push(new RankModel(userData, value.ttgame.score))
          }

        }
      }

    }
    for (const key in this.rankMap) {
      if (this.rankMap.hasOwnProperty(key)) {
        const element /*: RankModel[]*/ = this.rankMap[key];
        element.sort(function (a, b) {
          return b.getScore() - a.getScore();
        })
      }
    }
  }
}



let rankView = new RankView();

wx.onMessage(function (data) {

  if (data.event == "viewport") {
    // console.log(' data ', data)
    rankView.init(data.x, data.y, data.width, data.height);
  }
  if (data.message) {
    console.log(' data ', data)
    // if (data.message == DataEvent.INIT) {
    //   let value = data.value;
    //   console.log(' data ', data)
    //   rankView.init(0, 0, value.width, value.height);
    // } else 
    if (data.message == DataEvent.HIDE_VIEW) {
      // this.node.active = false
      render.isDirty = true
    } else if (data.message == DataEvent.SHOW_VIEW) {
      render.isDirty = false
      rankView.showView(data.value);
    } else if (data.message == DataEvent.SEND_DATA) {
      rankView.setData(data.value, data.channelID)
    } else if (data.message == DataEvent.CHANGE_DIR) {
      if (data.value == 1) {
        rankView.right();
      } else {
        rankView.left();
      }

    } else if (data.message == DataEvent.TURN_RIGHT) {

    }
  }
});